package com.yxw.yxnet_cd_center.customer_service.service.impl;

import com.yxw.yxnet_cd_center.common.enums.CodeRuleEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.PinyinUtill;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsCodeRuleEntity;
import com.yxw.yxnet_cd_center.customer_service.mapper.CodeRuleMapper;
import com.yxw.yxnet_cd_center.customer_service.service.CodeRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 编码规则
 * @author liuxin
 * @date 2023.09.20
 */
@Service
public class CodeRuleServiceImpl implements CodeRuleService {

    @Autowired
    private CodeRuleMapper  codeRuleMapper;


    /**
     *
     * @param name
     * @param rule
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized String buildCode(String name, CodeRuleEnum rule) {
        //先查询当前编码
        YxCsCodeRuleEntity entity = codeRuleMapper.getCodeRuleByType(rule.getCodeType());
        if(null==entity){
            throw new BaseException("查询编号规则异常");
        }
        //编码序号和版本修改,防止重复编码出现
        int count= codeRuleMapper.updateCodeRule(entity.getId(),entity.getVersion());
        if(count==0L){
            return "";
        }
        return PinyinUtill.getPinYinHeadChar(name)+entity.getCode();
    }
}
